package test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import test.domain.MenuItem;
import test.repository.MenuRepository;

@RestController
@Scope("prototype")
public class CopyOfTestController {

	private int a = 0;

	public CopyOfTestController() {
		System.out.println("I am live");
	}

	@Autowired
	@Qualifier(value = "testR")
	private MenuRepository menuRepository;

	@RequestMapping("/test2")
	public Object test(Object k) throws InterruptedException {
		TestNew ta = new TestNew();
		TestNew2 testNew2 = new TestNew2(ta);
		testNew2.start();
		ta.start();
		ta.join();
		System.out.println("thread:" + a);
		test.domain.MenuItem menuItem = new test.domain.MenuItem();
		menuItem.setDescription("hello");
		menuItem.setName("name");
		// menuRepository.save(menuItem);
		return menuItem;
	}

	@RequestMapping("/testBody2")
	@ResponseBody
	public MenuItem greeting(@RequestBody MenuItem muItem) {
		return muItem;
	}

	public class TestNew extends Thread {
		public void run() {
			synchronized (this) {
				try {

					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			for (int k = 0; k < 5; k++) {
				a = a + 1;
			}
		}
		
		public void wake(){
			synchronized (this) {
					this.notifyAll();
			}
		}
	}

	public class TestNew2 extends Thread {
		private TestNew testNew;

		public TestNew2(TestNew testNew) {
			this.testNew = testNew;
		}

		public void run() {
			try {
				sleep(2000l);
				testNew.wake();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
